﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Atlandiz.Data;
using System.IO;
using ExpertXls.ExcelLib;
using System.Data;
//using System.Security.AccessControl;

namespace Atlandiz.EnvanterVeZimmetYonetimi
{
    class Army
    {
        //Atlandiz
        public static string ProgramBaseCode = "ATLANDIZ02";
        public static string ProgramBaseEnvironmentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + ProgramBaseCode;
        public static string ProgramName = "Atlandiz Envanter Yönetimi";
        public static string ProgramVersion = "v.2.00 r1";
        public static string Serial = "";
        public static string LisansSahibi = "";
        public static string ExpDate = "";
        public static string Certificate = "";
        public static string LicenseClass = "";
        public static bool isMovable = false;
        public static string GorusBildirSecureKeyForAtlandiz = "GorusBildirSecureKeyForAtlandiz";
        public static LicenseServiceWS.LicenseService LicenseService = new LicenseServiceWS.LicenseService();
        //Atlandiz

        //SQL
        public static string SQLSunucu = "";
        public static string SQLVeritabani = "";
        public static string SQLUsername = "";
        public static string SQLPassword = "";
        public static bool SQLTrust = true;
        //SQL

        //EVENT
        public static bool EventConfirm = false;
        public static string EventMessage = "";
        
        public static string NewVTName = "";
        public static string NewVTServer = "";
        public static string NewVTUsername = "";
        public static string NewVTPassword = "";
        public static bool NewVTTrustConnection = false;
        //EVENT

        //OTHER GLOBAL PARAMS
        public static int ActiveUserId = 0;
        public static int UserTipi = 0;
        public static int SecilenID = 0;
        public static string Aciklama = "";
        public static string SecureKey = "ColdMaster1";
        //OTHER GLOBAL PARAMS

        //E-Mail Settings
        public static bool SendEmail = false;
        public static bool SslTlsZorunlu = false;

        public static string SenderName = "";
        public static string SenderEmail = "";
        public static string SmtpServer = "";
        public static string SmtpPort = "";
        public static string SmtpUsername = "";
        public static string SmtpPassword = "";
        public static string RecipientName = "";
        public static string RecipientEmail = "";
        public static string MessageHeaderPrefix = "";
        //E-Mail Settings

        //Report Settings
        public static string ReportForCihaz = "";
        public static string ReportForCihazListe = "";
        public static string ReportForYazilim = "";
        public static string ReportForYazilimListe = "";
        public static string ReportForZimmetGiris = "";
        public static string ReportForZimmetCikis = "";
        //Report Settings

        //Akış Settings
        //public static string ParaBirimi = "";
        //Akış Settings

        //FirmaHakkinda Settings
        public static string FirmaUnvan = "";
        public static string FirmaAdres = "";
        public static string FirmaTelefon = "";
        public static string FirmaEposta = "";
        public static string FirmaYetkiliAdSoyad = "";
        public static string FirmaYetkiliUnvan = "";
        //FirmaHakkinda Settings

        public static MsSqlAccessLayer SQL() {
            MsSqlAccessLayer newSQL;
            switch (SQLTrust) { 
                case true:
                    newSQL = new MsSqlAccessLayer(SQLSunucu, SQLVeritabani, true);
                    break;
                default:
                    newSQL = new MsSqlAccessLayer(SQLSunucu, SQLVeritabani, SQLUsername, SQLPassword);
                    break;            
            }
            return newSQL;
        }

        public static string GetSetting(string SettingKey,string defValue) {
            string Value="";
            try
            {
                Value = Army.SQL().GetDataCell("SELECT (CASE WHEN (SELECT TOP 1 Value FROM AppSettings WHERE Uid=" + ActiveUserId + " AND SettingKey='" + SettingKey + "')is NULL THEN '" + defValue + "' ELSE (SELECT TOP 1 Value FROM AppSettings WHERE Uid=" + ActiveUserId + " AND SettingKey='" + SettingKey + "') END) Value");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Veritabanı Erişimde Hata Oluştu..", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            return Value;
        }
        
        public static void SetSetting(string SettingKey, string Value, bool ForAllUsers)
        {
            try
            {
                if (int.Parse(Army.SQL().GetDataCell("Select count(*) from AppSettings Where Uid=" + Army.ActiveUserId + " AND SettingKey='" + SettingKey + "'")) > 0)
                {
                    if (ForAllUsers)
                    {
                        Army.SQL().cmd("Update AppSettings Set Value='" + Value.Replace("'", "''") + "' Where SettingKey='" + SettingKey + "'");
                    }
                    else {
                        Army.SQL().cmd("Update AppSettings Set Value='" + Value.Replace("'", "''") + "' Where Uid=" + Army.ActiveUserId + " AND SettingKey='" + SettingKey + "'");
                    }
                    
                }
                else
                {
                    Army.SQL().cmd("INSERT AppSettings (Uid,SettingKey,Value) VALUES(" + Army.ActiveUserId + ",'" + SettingKey + "','" + Value.Replace("'", "''") + "')");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Veritabanı Erişimde Hata Oluştu..", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        public static void MakeExcelFromDatatable(DataTable dt, String DosyaAd)
        {
            string outFilePath = null;
            ExcelWorkbookFormat workbookFormat = ExcelWorkbookFormat.Xlsx_2007;
            ExcelWorkbook workbook = new ExcelWorkbook(workbookFormat);
            ExcelWorksheet worksheet = workbook.Worksheets[0];
            worksheet.Name = "Data";

            outFilePath =  DosyaAd;
            worksheet.LoadDataTable(dt, 1, 1, true);

            string dateFormatString = "dd/MM/yyyy";
            int KolonSay = 0;

            int SatirSay = 1;
            foreach (DataRow x in dt.Rows)
            {
                SatirSay += 1;
                KolonSay = 0; //Sıfırlamak gerekli her satır'da..
                foreach (DataColumn y in dt.Columns)
                {
                    KolonSay += 1;
                    if (y.DataType.ToString() == "System.DateTime")
                    {
                        int kac = KolonSay;
                        worksheet[SatirSay, kac].Style.Number.NumberFormatString = dateFormatString;
                    }
                }
            }

            workbook.LicenseKey = "Bi02JjU0JjYmNyg2JjU3KDc0KD8/Pz8=";

            workbook.DocumentProperties.Subject = "Atlandiz";
            workbook.DocumentProperties.Comments = "Bu dosya Atlandiz uygulamaları tarafından üretilmiştir.";

            worksheet.AutofitColumns();
            try
            {
                workbook.Save(outFilePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                workbook.Close();
                #region Dispose the Image object
                //if (logoImg != null)
                //    logoImg.Dispose();
                #endregion
            }

        }


        public static void StartupEvents()
        {
            IniAccessLayer ini = new IniAccessLayer(ProgramBaseEnvironmentPath + "\\Tanimlar.ini");

            Army.SQLSunucu = ini.ReadString("Veritabani", "SqlSunucu");
            Army.SQLVeritabani = ini.ReadString("Veritabani", "SqlVeritabani");
            Army.SQLUsername = ini.ReadString("Veritabani", "SqlKullaniciAdi");
            Army.SQLPassword = ini.ReadString("Veritabani", "SqlParola");
            Army.SQLTrust = ini.ReadBoolean("Veritabani", "UseTrustConnection");

            Army.SendEmail = ini.ReadBoolean("EPosta", "SendEmail");
            Army.SslTlsZorunlu = ini.ReadBoolean("EPosta", "SslTlsZorunlu");
            Army.SenderName = ini.ReadString("EPosta", "SenderName");
            Army.SenderEmail = ini.ReadString("EPosta", "SenderEmail");
            Army.SmtpServer = ini.ReadString("EPosta", "SmtpServer");
            Army.SmtpPort = ini.ReadString("EPosta", "SmtpPort");
            Army.SmtpUsername = ini.ReadString("EPosta", "SmtpUsername");
            Army.SmtpPassword = ini.ReadString("EPosta", "SmtpPassword");
            Army.RecipientName = ini.ReadString("EPosta", "RecipientName");
            Army.RecipientEmail = ini.ReadString("EPosta", "RecipientEmail");
            Army.MessageHeaderPrefix = ini.ReadString("EPosta", "MessageHeaderPrefix");

            Army.ReportForCihaz = ini.ReadString("Raporlar", "ReportForCihaz","\\Raporlar\\CihazEtiketi.frx");
            Army.ReportForCihazListe = ini.ReadString("Raporlar", "ReportForCihazListe", "\\Raporlar\\CihazListe.frx");
            Army.ReportForYazilim = ini.ReadString("Raporlar", "ReportForYazilim","\\Raporlar\\YazilimEtikleti.frx");
            Army.ReportForYazilimListe = ini.ReadString("Raporlar", "ReportForYazilimListe", "\\Raporlar\\YazilimListe.frx");
            Army.ReportForZimmetGiris = ini.ReadString("Raporlar", "ReportForZimmetGiris", "\\Raporlar\\ZimmetGirisTutanagi.frx");
            Army.ReportForZimmetCikis = ini.ReadString("Raporlar", "ReportForZimmetCikis", "\\Raporlar\\ZimmetCikisTutanagi.frx");

            Army.GorusBildirSecureKeyForAtlandiz = Atlandiz.Data.Hash.ComputeHash(GorusBildirSecureKeyForAtlandiz, "SHA1", null);

            Army.SecureKey = Atlandiz.Data.Hash.ComputeHash(SecureKey, "SHA1", null);
        }

        public static bool CreateProgramDefaultFiles() {
            
            bool rt = false;
            try
            {
                //TEMP DIRECTORY (Atlandiz)
                if (!Directory.Exists(@Application.StartupPath + "\\Temp"))
                {
                    Directory.CreateDirectory(@Application.StartupPath + "\\Temp");
                }

                //MASTER DIRECTORY (Atlandiz)
                if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz"))
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz");
                }
                
                //BASE DIRECTORY
                if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode))
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode);
                }

                //REPORTS DIRECTORY
                if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode + "\\Raporlar"))
                {
                    Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode + "\\Raporlar");
                }

                //COPY REPORTS FILES
                string[] filePaths = Directory.GetFiles(Application.StartupPath + "\\Raporlar", "*.*");
                foreach (string x in filePaths)
                {
                    //FileSecurity fSecurity = File.GetAccessControl(x);

                    //// Add the FileSystemAccessRule to the security settings.
                    //fSecurity.AddAccessRule(new FileSystemAccessRule("Atlandiz", FileSystemRights.FullControl, AccessControlType.Allow));

                    //// Set the new access settings.
                    //File.SetAccessControl(x, fSecurity);

                    FileInfo fileN = new FileInfo(x);
                    if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode + "\\Raporlar\\" + fileN.Name))
                    {                      
                        fileN.CopyTo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode + "\\Raporlar\\" + fileN.Name, false);                    
                    }
                }

                //Config File
                if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode + "\\Tanimlar.ini"))
                {
                    IniAccessLayer ini = new IniAccessLayer(ProgramBaseEnvironmentPath + "\\Tanimlar.ini");
                    ini.Write("Raporlar", "ReportForCihaz", "\\Raporlar\\CihazEtiketi.frx");
                    ini.Write("Raporlar", "ReportForCihazListe", "\\Raporlar\\CihazListe.frx");
                    ini.Write("Raporlar", "ReportForYazilim", "\\Raporlar\\YazilimEtiketi.frx");
                    ini.Write("Raporlar", "ReportForYazilimListe", "\\Raporlar\\YazilimListe.frx");
                    ini.Write("Raporlar", "ReportForZimmetGiris", "\\Raporlar\\ZimmetGirisTutanagi.frx");
                    ini.Write("Raporlar", "ReportForZimmetCikis", "\\Raporlar\\ZimmetCikisTutanagi.frx"); 
                }

                //License File
                if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode + "\\License.ini"))
                {
                    File.Create(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Atlandiz\\" + Army.ProgramBaseCode + "\\License.ini");
                }

                rt = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Hata Oluştu:\n" +  ex.Message.ToString(), "Erişim Hatası", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
            return rt;
        }

        public static bool CheckInterConnection()
        {
            string url = Army.LicenseService.Url;
            try
            {
                System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url);
                System.Net.WebResponse myResponse = myRequest.GetResponse();
            }
            catch (System.Net.WebException)
            {
                return false;
            }
            return true;
        }

        public static void SetFreshConfig() {
            IniAccessLayer ini = new IniAccessLayer(ProgramBaseEnvironmentPath + "\\Tanimlar.ini");
            ini.Write("Raporlar", "ReportForCihaz", "\\Raporlar\\CihazEtiketi.frx");
            ini.Write("Raporlar", "ReportForCihazListe", "\\Raporlar\\CihazListe.frx");
            ini.Write("Raporlar", "ReportForYazilim", "\\Raporlar\\YazilimEtiketi.frx");
            ini.Write("Raporlar", "ReportForYazilimListe", "\\Raporlar\\YazilimListe.frx");
            ini.Write("Raporlar", "ReportForZimmetGiris", "\\Raporlar\\ZimmetGirisTutanagi.frx");
            ini.Write("Raporlar", "ReportForZimmetCikis", "\\Raporlar\\ZimmetCikisTutanagi.frx");        
        }

        public static void GetLicenseInformation() {
            IniAccessLayer ini = new IniAccessLayer(ProgramBaseEnvironmentPath + "\\License.ini");
            Army.Serial = ini.ReadString("License", "Serial");
            Army.ExpDate = ini.ReadString("License", "ExpireDate", "01.01.2010");
            Army.Certificate = ini.ReadString("License", "Certificate");
            Army.LisansSahibi = ini.ReadString("License", "CariUnvan");
            Army.LicenseClass = ini.ReadString("License", "LicenseClass");
            Army.isMovable = ini.ReadBoolean("License", "isMovable", false);
        }

        public static void StartupEventsAfterLogin()
        {
            Army.FirmaUnvan = Army.GetSetting("FirmaUnvan", "");
            Army.FirmaAdres = Army.GetSetting("FirmaAdres", "");
            Army.FirmaTelefon = Army.GetSetting("FirmaTelefon", "");
            Army.FirmaEposta = Army.GetSetting("FirmaEposta", "");
            Army.FirmaYetkiliAdSoyad = Army.GetSetting("FirmaYetkiliAdSoyad", "");
            Army.FirmaYetkiliUnvan = Army.GetSetting("FirmaYetkiliUnvan", "");
        }
    }
}
